package com.lx.idea.controller;

import com.lx.idea.common.Constant;
import com.lx.idea.common.dto.ResponseCode;
import com.lx.idea.common.dto.ResponseModel;
import com.lx.idea.common.util.TokenUtil;
import com.lx.idea.service.NodeServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author ybb
 * @Description
 * @Date 2021/8/31 15:43
 */
@RestController
@RequestMapping("/token")
@Api(tags = "token接口")
public class TokenController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    NodeServiceImpl nodeService;

    @Autowired
    TokenUtil tokenUtil;

    @GetMapping("/get")
    @ApiOperation(value = "三级节点获取token", httpMethod = "GET", produces = "application/json", response = ResponseModel.class)
    public ResponseModel get(HttpServletRequest request){
        String key = request.getHeader(Constant.key);
        String secret = request.getHeader(Constant.secret);
        try {
            if (StringUtils.isAllBlank(key, secret) ||
                    ObjectUtils.isEmpty(nodeService.getAppUser(key, secret))) {
                return ResponseModel.error(ResponseCode.AUTH_HEADER_ERROR, ResponseCode.AUTH_HEADER_ERROR.getMessage());
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResponseModel.error(ResponseCode.SYS_ERROR, ResponseCode.SYS_ERROR.getMessage());
        }

        return ResponseModel.success(tokenUtil.genToken(key+"_"+secret));
    }
}
